﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace System.Security.Cryptography
{
    public static class RSAHelp
    {
        /// <summary>
        /// 将字符串使用RSA方式加密
        /// </summary>
        /// <param name="encriptData">待加密字符串</param>
        /// <param name="certBuffer">cer证书，用来提出公钥</param>
        /// <returns>加密后的base64字符串</returns>
        public static string RSAEncriptWithCert(string encriptData, byte[] certBuffer)
        {
            X509Certificate cer = new X509Certificate(certBuffer);
            RSAParameters RSAKeyInfo = X509PublicKeyParser.GetRSAPublicKeyParameters(cer.GetPublicKey());

            BigInteger bi_e = new BigInteger(RSAKeyInfo.Exponent);
            BigInteger bi_n = new BigInteger(RSAKeyInfo.Modulus);
            BigInteger bi_data = new BigInteger(System.Text.Encoding.UTF8.GetBytes(encriptData));
            BigInteger bi_encrypted = bi_data.modPow(bi_e, bi_n);
            //rsa加密后的Base64字符串
            string rsaEncryptString = Convert.ToBase64String(bi_encrypted.getBytes());
            return rsaEncryptString;
        }
    }
}
